

// 函数的单例
function Singleton() {
    // 判断是否存在实例
    if (typeof Singleton.instance === "object") {
      return Singleton.instance;
    }
  
    // 初始化单例对象
    this.property1 = "value1";
    this.property2 = "value2";
    Singleton.instance = this;
  }
  
  const instance1 = new Singleton();
  const instance2 = new Singleton();
  
  console.log(instance1 === instance2); // 输出 true
  

// 类的单例
class SingletonClass {
    constructor() {
        if (SingletonClass.instance) {
            return SingletonClass.instance;
        }
        this.property1 = "value1";
        this.property2 = "value2";
        SingletonClass.instance = this;
    }
}

const instance3 = new SingletonClass();
const instance4 = new SingletonClass();

console.log(instance3 === instance4); // true




// 特殊的一些用法
function test() {
    class A {
        constructor() {
            if (A.instance) {
                return A.instance;
            }
            A.instance = this;
            this.name = 'A';
        }


        getName() {
            return this.name;
        }

        setName(name) {
            this.name = name;
        }
    }

    function getInstance() {
        if (!test.instance) {
            test.instance = new A();
        }
        return test.instance; 
    }

    return {
        getInstance
    }


    // if (!test.instance) {
    //     test.instance = new A();
    // }
    // return test.instance;  // 返回单例实例

    // return new A(); // 每次调用都会创建一个新的实例
}

const instance5 = test().getInstance();
instance5.setName('New Name');
const instance6 = test().getInstance();
instance6.getName(); // 'New Name'

console.log(instance5 === instance6); // true, 因为 test() 返回的是同一个实例